package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.query.ChartQueryObject;
import cn.wolfcode.crm.service.IChartService;
import cn.wolfcode.crm.util.JSONUtil;
import cn.wolfcode.crm.util.MessageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/chart")
public class ChartController {
    @Autowired
    private IChartService chartService;

    @RequestMapping("/list")
    public String list(@ModelAttribute("qo") ChartQueryObject qo, Model model) {
        model.addAttribute("list", chartService.listChart(qo));
        return "chart/list";
    }

    @RequestMapping("/bar")
    public String getChartBar(@ModelAttribute("qo") ChartQueryObject qo, Model model) {
        List<Map<String, Object>> list = chartService.listChart(qo);
        //共享分组类型
        model.addAttribute("groupType", MessageUtil.changMsg(qo));
        //["admin", "bunny", "赵总"]
        List<Object> x = new ArrayList<>();
        //[3,2,4]
        List<Object> y = new ArrayList<>();
        for (Map<String, Object> map : list) {
            x.add(map.get("groupType"));
            y.add(map.get("totalNumber"));
        }
        model.addAttribute("x", JSONUtil.toJSONString(x));
        model.addAttribute("y", JSONUtil.toJSONString(y));
        return "chart/bar";
    }

    @RequestMapping("/pie")
    public String getChartPie(@ModelAttribute("qo") ChartQueryObject qo, Model model) {
        List<Map<String, Object>> list = chartService.listChart(qo);
        //共享分组类型
        model.addAttribute("groupType", MessageUtil.changMsg(qo));
        //["admin", "bunny", "赵总"]
        List<Object> legendData = new ArrayList<>();
        /*
          [
            {value:5, name:"admin"},
            {value:3, name:"赵总"},
            {value:7, name:"赵一明"}
          ]
         */
        List<Object> datas = new ArrayList<>();
        for (Map<String, Object> map : list) {
            Object name = map.get("groupType");
            legendData.add(name);
            //{value:5, name:"admin"}
            Map<String, Object> data = new HashMap<>();
            data.put("name", name);
            data.put("value", map.get("totalNumber"));
            datas.add(data);
        }
        model.addAttribute("legendData", JSONUtil.toJSONString(legendData));
        model.addAttribute("datas", JSONUtil.toJSONString(datas));
        return "chart/pie";
    }
}
